package com.homework.task;

import com.homework.mapper.HomeworkMapper;
import com.homework.entity.Homework;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class HomeworkTask {

    private final HomeworkMapper homeworkMapper;

    /**
     * 每5分钟检查一次当前应该显示的作业
     */
    @Scheduled(fixedRate = 5 * 60 * 1000) // 5分钟执行一次
    public void checkCurrentHomework() {
        try {
            LocalDateTime now = LocalDateTime.now();

            // 查找所有未完成且过期的作业，标记为过期
            List<Homework> expiredHomework = homeworkMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Homework>()
                    .lt(Homework::getEndTime, now)
                    .in(Homework::getStatus, 0, 1) // 未开始或进行中
            );

            for (Homework homework : expiredHomework) {
                log.info("作业已过期: {}", homework.getTitle());
                // 这里可以发送通知或记录日志
            }

            log.debug("定时检查当前作业完成，检查时间: {}", now);

        } catch (Exception e) {
            log.error("定时检查当前作业发生错误", e);
        }
    }
}